<?php
# http://projects:8081/cdapp-2kt-api/api/activity_general_load.php
include_once './_portal.php';
include_once './request_sipds.php';

const MIN_TTL    = 15 * 1000; # unit: ms
const MAX_TTL    = 30 * 1000; # unit: ms
const PARAM_NAME = 'activityGeneralRefreshTime';
const API_NAMES  = [
  'generalAviationWebService.findGeneralAviationPage(Pending)',
  'generalAviationWebService.findGeneralAviationPage(Active)',
];

$refresh_info = get_param(PARAM_NAME);
$ttl_verify   = verify_ttl($refresh_info['tx'], $refresh_info['rx'], MIN_TTL, MAX_TTL);
$info         = 'activity_general_load: ' . $ttl_verify['info'];
$status       = $ttl_verify['status'];
$time         = $ttl_verify['time'];

$history = null;

if ($status > 0) {
  save_param(PARAM_NAME, ['tx' => $time, 'rx' => $refresh_info['rx']]);
  $request_result = refresh_data(API_NAMES);
  $info .= ' ' . $request_result['info'];
  $status  = $status * $request_result['status'];
  $history = $request_result['history'] ?? null;
  $time_rx = timestamp();
  save_param(PARAM_NAME, ['tx' => $time, 'rx' => $time_rx]);
}

output([
  'status'  => $status,
  'info'    => $info,
  'data'    => exec_sql("SELECT * FROM `2kt_activity_general`"),
  'history' => $history,
]);

die();

# request content from sipds
function refresh_data($api_names = []) {
  $sql_arr = ["TRUNCATE TABLE `2kt_activity_general`"];
  $result  = true;
  for ($i = 0; $i < count($api_names); $i++) {
    $status   = $i;
    $api_name = $api_names[$i];
    $response = request_sipds($api_name);
    if ($response['status'] == 0) {
      return [
        'status' => 0,
        'info'   => 'Failed to refresh data, sending request failed.',
      ];
    }
    if (! isset($response['data']['CONTENTS']) || $response['data']['CONTENTS'] == null) {
      // return [
      //   'status' => 0,
      //   'info' => 'Failed to refresh data, recived null response.',
      // ];
    } else {
      $sql = "INSERT INTO `2kt_activity_general` (`number`, `name`, `callsign`, `sqawk`, `level`, `area`, `ATD`, `status`) VALUES ";
      foreach ($response['data']['CONTENTS'] as $res) {
        $element = [
          'name'     => isset($res['MISSIONNAME']) ? $res['MISSIONNAME'] : '',
          'callsign' => isset($res['CALLSIGN']) ? $res['CALLSIGN'] : '',
          'acType'   => isset($res['ACTYPE']) ? $res['ACTYPE'] : '',
          'sqawk'    => isset($res['TRANSPONDER']) ? $res['TRANSPONDER'] : '',
          'level'    => isset($res['FLIGHTHEIGHT']) ? $res['FLIGHTHEIGHT'] : '',
          'area'     => isset($res['WORKAREA']) ? $res['WORKAREA'] : '',
          'arrField' => isset($res['ARRAIRPORT']) ? $res['ARRAIRPORT'] : '',
          'depField' => isset($res['DEPAIRPORT']) ? $res['DEPAIRPORT'] : '',
          'ATD'      => isset($res['ATD']) ? substr($res['ATD'], 0, 10) . ' ' . substr($res['ATD'], 11, 8) : '',
          'status'   => $status,
        ];
        $sql .= "(null, '{$element['name']}', '{$element['callsign']}', '{$element['sqawk']}', '{$element['level']}', '{$element['area']}', '{$element['ATD']}', '{$element['status']}'),";
      }
      $sql = rtrim($sql, ',');
      array_push($sql_arr, $sql);
    }
  }
  $result_arr = exec_sql_array($sql_arr);
  foreach ($result_arr as $r) {
    $result = $result && $r;
  }

  // ================================================
  // added history record function@2025/7/26
  $res_his = update_activity_history();
  // ================================================

  if ($result) {
    return [
      'status'  => 1,
      'info'    => 'Successed to refresh data.',
      'history' => $res_his,
    ];
  } else {
    return [
      'status'  => 0,
      'info'    => 'Failed refresh data, database update filed.',
      'history' => $res_his,
    ];
  }
}

function update_activity_history() {
  // added history record function@2025/7/26
  // 新建记录表
  exec_sql("CREATE TABLE IF NOT EXISTS `cdapp`.`2kt_activity_history` (`number` INT(8) NOT NULL AUTO_INCREMENT , `unit` TEXT NOT NULL , `callsign` TEXT NOT NULL , `category` VARCHAR(4) NOT NULL , `startTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP , `endTime` DATETIME NULL DEFAULT NULL , `flightCount` INT(5) NOT NULL DEFAULT '0' , PRIMARY KEY (`number`)) ENGINE = InnoDB");

  $sql_query_current_activity = "SELECT * FROM `2kt_activity_general` WHERE `status` = 1";
  $current_activity           = exec_sql($sql_query_current_activity);
  $current_activity           = $current_activity ?: [];

  $sql_query_rcorded_activity = "SELECT * FROM `2kt_activity_history` WHERE `endTime` IS NULL AND `category` = 'G'";
  $rcorded_activity           = exec_sql($sql_query_rcorded_activity);
  $rcorded_activity           = $rcorded_activity ?: [];

  $need_add = [];
  $need_end = [];

  $need_add_callsign = [];
  $need_end_callsign = [];

  $now_time = date('Y-m-d H:i:s');

  // 需要添加的活动记录
  foreach ($current_activity as $current_item) {
    $is_recorded = false;
    foreach ($rcorded_activity as $recorded_item) {
      if ($current_item['callsign'] == $recorded_item['callsign']) {
        $is_recorded = true;
        break;
      }
    }
    if (! $is_recorded) {
      $callsign = $current_item['callsign'];
      // $unit                = preg_replace('/\d+/', '', $callsign);
      $unit                = keepOnlyChinese($callsign);
      $need_add_callsign[] = $callsign;
      $need_add[]          = "INSERT INTO `2kt_activity_history` (`unit`,`callsign`,`category`,`startTime`) VALUES ('{$unit}','{$callsign}','G','{$now_time}')";
    }
  }

  // 需要结束的活动记
  foreach ($rcorded_activity as $recorded_item) {
    $is_active = false;
    foreach ($current_activity as $current_item) {
      if ($current_item['callsign'] == $recorded_item['callsign']) {
        $is_active = true;
        break;
      }
    }
    if (! $is_active) {
      $number              = $recorded_item['number'];
      $need_end_callsign[] = $recorded_item['callsign'];
      $need_end[]          = "UPDATE `2kt_activity_history` SET `endTime` = '{$now_time}' WHERE `number` = {$number}";
    }

  }

  $results_add = [];
  $results_end = [];

  if (count($need_add) > 0) {
    $results_add = exec_sql_array($need_add);
  }

  if (count($need_end) > 0) {
    $results_end = exec_sql_array($need_end);
  }

  $result_add = ! in_array(false, $results_add, true);
  $result_end = ! in_array(false, $results_end, true);

  $output = [
    'callsignAdded' => $need_add_callsign,
    'callsignEnded' => $need_end_callsign,
    'statusAdd'     => $result_add,
    'statusEnd'     => $result_end,
    'sqlAdd'        => $result_add ? '' : $need_add,
    'sqlEnd'        => $result_end ? '' : $need_end,
  ];

  return $output;

}